package com.haiyou.common.util;


import com.haiyou.common.constant.MessageCode;
import com.haiyou.common.exception.BusinessException;

import java.util.HashMap;


/**
 * 返回数据
 */
public class R extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;
    private static final String MESSAGE = "message";
    private static final String CODE = "code";
    private static final String DATA = "data";

    public static R ok() {
        R r = new R();
        r.put(CODE, MessageCode.SUCCESS.getCode());
        r.put(MESSAGE, MessageCode.SUCCESS.getMessage());
        return r;
    }

    public static R ok(Object data) {
        R r = new R();
        r.put(CODE, MessageCode.SUCCESS.getCode());
        r.put(MESSAGE, MessageCode.SUCCESS.getMessage());
        r.put(DATA, data);
        return r;
    }

    public static R error(int code, String msg) {
        R r = new R();
        r.put(CODE, code);
        r.put(MESSAGE, msg);
        return r;
    }

    public static R error(String msg) {
        R r = new R();
        r.put(CODE, MessageCode.VALID_PARAMS_ERROR.getCode());
        r.put(MESSAGE, msg);
        return r;
    }

    public static R error(MessageCode messageCode) {
        R r = new R();
        r.put(CODE, messageCode.getCode());
        r.put(MESSAGE, messageCode.getMessage());
        return r;
    }

    public static R error(int code, String msg, Object data) {
        R r = new R();
        r.put(CODE, code);
        r.put(MESSAGE, msg);
        r.put(DATA, data);
        return r;
    }

    public static R error() {
        R r = new R();
        r.put(CODE, MessageCode.ERROR.getCode());
        r.put(MESSAGE, MessageCode.ERROR.getMessage());
        return r;
    }

    public void validate() {
        int code = Integer.parseInt(this.get("code").toString());
        if (code != MessageCode.SUCCESS.getCode()) {
            throw new BusinessException(code, this.get("code").toString());
        }
    }
}
